<template>
    <BasicModal v-bind="$attrs" @register="registerModal" :title="modalTitle" @ok="onButtonOkClick">
        <BasicForm @register="registerAddForm" />
    </BasicModal>
</template>
<script lang="ts">
import { defineComponent, ref, unref, inject } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { studentFormSchema } from './student.data';
import { addStudent, getStudent, updateStudent, queryAllClass } from '/@/api/demo/student';
import { useMessage } from '/@/hooks/web/useMessage';
import { OperationTypeEnum } from '/@/enums/appEnum';
// const { createMessage, createErrorModal } = useMessage();
const { createMessage } = useMessage();

export default defineComponent({
    name: 'AddStudent',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
        //调用后台接口获取部门信息进行部门列表赋值
        //获取定义的表单，设置其中需要动态加载的部门数据列表
        const addStudentFormSchema = studentFormSchema;

        //弹出窗口界面是新增数据、修改数据还是重新处理数据；根据传递过来的参数进行判断
        const op = ref(OperationTypeEnum.UN_KNOWN);
        const dataId = ref('');
        const moduleName = inject<string>('moduleName');
        //标题--根据传入的模块名称+操作类型组合得到
        const modalTitle = ref('标题');

        const [registerAddForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
            labelWidth: 100,
            schemas: addStudentFormSchema,
            showActionButtonGroup: false,
            actionColOptions: {
                span: 23,
            },
        });

        const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
            //根据传递过来的参数获取对应的操作，操作不同所对应的界面不同
            //接收父组件传递的数据
            if (data?.op) {
                //判断是否传入op属性
                op.value = data.op;
            }
            if (data?.dataId) {
                dataId.value = data.dataId;
            }

            if (moduleName) {
                modalTitle.value = unref(moduleName);
            }
            if (op.value != OperationTypeEnum.UN_KNOWN && op.value != OperationTypeEnum.CUSTOME) {
                modalTitle.value += '--' + op.value;
            }

            resetFields();
            setModalProps({ confirmLoading: false });

            if (op.value == OperationTypeEnum.ADD) {
                getAllValidClass();
            }
            //如果是修改数据，根据传入的id获取数据后进行赋值
            else if (op.value == OperationTypeEnum.EDIT) {
                getStudent({ no: dataId.value })
                    .then((res) => {
                        console.log('res', res);
                        setFieldsValue({
                            ...res,
                            sex: res.sex ? '男' : '女'
                        });
                        if (res.classCode != null && res.classCode.length > 0x0) {
                            getAllValidClass();
                        }
                    })
                    .catch((ex) => {
                        console.log('catch ', ex);
                        createMessage.error(ex.msg);
                    });
            }
        });

        function getAllValidClass() {
            queryAllClass()
                .then((res) => {
                    console.log('res', res);
                    let classOptions = [];
                    for (let d of res) {
                        classOptions.push({ value: d.no, label: d.name });
                    }

                    updateSchema({
                        field: 'classCode',
                        componentProps: {
                            options: classOptions,
                        },
                    });
                })
                .catch((ex) => {
                    console.log('catch ', ex);
                    createMessage.error(ex.msg);
                });
        }

        async function onButtonOkClick() {
            //根据指定的操作类型分别进行提交数据和处理
            if (op.value == OperationTypeEnum.ADD) {
                //对应操作的步骤为：验证表单、提交后台保存、关闭modal、调用父组件事件刷新数据
                try {
                    const values = await validate();
                    setModalProps({ confirmLoading: true });
                    if (values.sex == '男') values.sex = true;
                    else values.sex = false;
                    //调用接口进行保存
                    addStudent(values)
                        .then((res) => {
                            if (!res || Object.keys(res).length == 0) {
                                createMessage.success('保存成功。', 2);
                            }
                            closeModal();
                            emit('success');
                            // emit('success', {
                            //   isUpdate: unref(isUpdate),
                            //   values: { ...values, id: rowId.value },
                            // });
                        })
                        .catch((ex) => {
                            console.log('catch ', ex);
                            createMessage.error(ex.msg);
                        });
                } finally {
                    setModalProps({ confirmLoading: false });
                }
            } else if (op.value == OperationTypeEnum.EDIT) {
                const values = await validate();
                if (values.sex == '男') values.sex = true;
                else values.sex = false;
                setModalProps({ confirmLoading: true });
                //调用接口进行保存
                updateStudent(values)
                    .then((res) => {
                        if (!res || Object.keys(res).length == 0) {
                            createMessage.success('保存成功。', 2);
                        }
                        closeModal();
                        emit('success');
                    })
                    .catch((ex) => {
                        console.log('catch ', ex);
                        createMessage.error(ex.msg);
                    });
            } else {
                createMessage.error('当前操作类型错误，无法进行对应操作。', 5);
            }
        }

        return {
            op,
            moduleName,
            modalTitle,
            registerModal,
            registerAddForm,
            getAllValidClass,
            onButtonOkClick,
        };
    },
});
</script>
